package com.hzlx.dao;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @author 86166
 * @version 1.0
 * @description: TODO
 * @date 2023/4/9 22:34
 */
public class ConnectionPool {
    static LinkedList<Connection> connectionPool = new LinkedList<>();
    static String url="jdbc:mysql://127.0.0.1:3306/order_food_db?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&usePrepStmts=true&cachePrepStmts=true&rewriteBatchedStatements=true";
    static String userName = "root";
    static String password = "root";
    static String driver = "com.mysql.cj.jdbc.Driver";
    static {
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        initConnectionPool();
    }
    public static void initConnectionPool(){
        for (int i = 0; i < 10; i++){
            Connection connection = null;
            try {
                connection = DriverManager.getConnection(url,userName,password);
            } catch (SQLException e) {
                e.printStackTrace();
            }
            connectionPool.addLast(connection);
        }
    }
    public static Connection getConnection(){
        Connection connection = null;
        if (connectionPool.size()>0){
            connection = connectionPool.removeFirst();
        }else {
            try {
                connection = DriverManager.getConnection(url,userName,password);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return connection;
    }
    public static void returnConnection(Connection connection){
        if (connectionPool.size()<10){
            connectionPool.addLast(connection);
        }else {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
